package Demo1;

// 阻塞队列

class Blocked{
    private String[] elems = null;
    private int front = 0;//队头
    private int rear = 0;//队尾
    private int size = 0;//元素个数
    private static  Object locker = new Object();

    public Blocked(int capacity){
//        构造函数 构造容量
        elems = new String[capacity];
    }
   public void put(String elem) throws InterruptedException {
//        入队列
       synchronized (locker) {
           while (size >= elems.length){
    //           满了 需要阻塞等待
               locker.wait();
           }
           elems[rear] = elem;
           rear = (rear+1)% elems.length;
           locker.notifyAll();
           size++;
       }
   }
   public String take() throws InterruptedException {
       String e = null;
       synchronized (locker) {
           while (size == 0) {
//                队列为空 等待元素插入再取出元素
               locker.wait();
           }
           e = elems[front];
           front = (front + 1) % elems.length;
           size--;
           locker.notifyAll();//可以避免死锁
       }
       return e;
   }
}
public class T28 {
    public static void main(String[] args) throws InterruptedException {
        Blocked blocked = new Blocked(100);
//        生产者

        Thread thread = new Thread(()->{
            int n = 1;
            while(true){{
                try {
                    blocked.put("n: "+n);
                    System.out.println("生产了: "+n);
                    Thread.sleep(5000);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }}
        });
        Thread t = new Thread(()->{
            while(true){
                try {
                    String s = blocked.take();
                    System.out.println("消费了 "+s);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        t.start();
    }
}
